package com.example.mq.mqserver.core;

import com.example.mq.common.ConsumerEnv;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class MSGQueue {

    //队列唯一ID
    private String name;

    //持久化
    private boolean durable;
    //是否独占（只能被一个消费者使用）
    private boolean exclusive;
    //没人使用自动删除
    private boolean autoDelete;
    //选项（扩展）
    private Map<String, Object> arguments = new HashMap<String, Object>();

    //当前队列有那些消费者订阅
    private List<ConsumerEnv> consumerEnvs = new ArrayList<ConsumerEnv>();

    //记录当前取到的第几个消费者
    private AtomicInteger consumerSeq=new AtomicInteger(0);//保证消费订阅线程安全

    //添加一个新的订阅者
    public void addConsumer(ConsumerEnv env) {
            synchronized (this) {
                consumerEnvs.add(env);
            }
    }

    //订阅删除暂时不考虑

    //挑选一个订阅者，处理当前消息(轮询的方式)
    public ConsumerEnv getConsumerEnv() {
        //还没有订阅者
        if(consumerEnvs.isEmpty()) {
            return null;
        }
        int index=consumerSeq.get()%consumerEnvs.size();
        consumerSeq.getAndIncrement();
        return consumerEnvs.get(index);

    }


    public boolean isDurable() {return durable;}

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isExclusive() {
        return exclusive;
    }

    public void setExclusive(boolean exclusive) {
        this.exclusive = exclusive;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }

    public String getArguments() {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    public void setArguments(String arguments) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            this.arguments = mapper.readValue(arguments, new TypeReference<Map<String, Object>>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    //直接赋值对象
    public void setArguments(Map<String, Object> arguments) {
        this.arguments = arguments;
    }

    public Object getArguments(String key) {
        return arguments.get(key);
    }

    public void setArguments(String key, Object value) {
        arguments.put(key, value);
    }


}
